﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SwAddinHelpers.Base;
using SwAddinHelpers.Attributes;

using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;

namespace SwAddinHelpers.Base
{
    [ComVisible(true)]
    public class ActiveXUserControlBase : UserControlBase
    {
        /*
        /// <summary>
        /// Invoked by SW App sink when PMP is closed, CONTROLID is used to find this method.
        /// </summary>
        /// <param name="Reason"></param>
        [InvokableMethod("StaticMethod.PropertyManagerPageCloseNotify")]
        protected virtual void PropertyManagerPageCloseNotify(int Reason) { }
        */ 

        [ComRegisterFunctionAttribute]
        public static void RegisterClass(string key)
        {
            // Strip off HKEY_CLASSES_ROOT\ from the passed key as I don't need it

            StringBuilder sb = new StringBuilder(key);
            sb.Replace(@"HKEY_CLASSES_ROOT\", "");

            // Open the CLSID\{guid} key for write access

            RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(), true);

            // And create the 'Control' key - this allows it to show up in 

            // the ActiveX control container 

            RegistryKey ctrl = k.CreateSubKey("Control");
            ctrl.Close();

            // Next create the CodeBase entry - needed if not string named and GACced.

            RegistryKey inprocServer32 = k.OpenSubKey("InprocServer32", true);
            inprocServer32.SetValue("CodeBase", Assembly.GetExecutingAssembly().CodeBase);
            inprocServer32.Close();

            // Finally close the main key

            k.Close();
        }

        [ComUnregisterFunctionAttribute]
        public static void UnregisterClass(string key)
        {
            try
            {
                StringBuilder sb = new StringBuilder(key);
                sb.Replace(@"HKEY_CLASSES_ROOT\", "");

                // Open HKCR\CLSID\{guid} for write access

                RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(), true);

                // Delete the 'Control' key, but don't throw an exception if it does not exist

                k.DeleteSubKey("Control", false);

                // Next open up InprocServer32

                RegistryKey inprocServer32 = k.OpenSubKey("InprocServer32", true);

                // And delete the CodeBase key, again not throwing if missing 

                k.DeleteSubKey("CodeBase", false);

                // Finally close the main key 

                k.Close();
            }
            catch {}
        }
    }
}
